package com.gdth.bank.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.adapter.DzCpKhListViewAdapter;
import com.gdth.bank.bean.DzCpItem;
import com.gdth.bank.presenter.DzCpKhXxEtcPresenter;
import com.gdth.bank.utils.ServerUtil;
import com.gdth.bank.view.DzCpKhXxEtcView;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.DzCpkhXxDjEtc;
import com.gdth.database.bean.TAppYh;
import com.gdth.database.bean.TXtBm;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshListView;

public class DzCpKhXxPosListActivity extends BaseActivity implements DzCpKhXxEtcView {
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
    @ViewInject(id=R.id.header_btn_right, click="addClick") TextView txt_header_right;
    @ViewInject(id=R.id.dzcpkhxx_query, click="queryClick") TextView txt_query;
    @ViewInject(id=R.id.dzcp_editTextNote) EditText edit_query;
	@ViewInject(id=R.id.listView) PullToRefreshListView listView;
	ListView mListView;
	List<DzCpItem> listData;
	DzCpKhListViewAdapter mAdapter;
	List<DzCpkhXxDjEtc> dzcpkhxxetcList;
	/** 提示框 */
    ProgressDialog mProgressDialog;
    DzCpKhXxEtcPresenter  mDzCpKhXxEtcPresenter;
    private String offset="1";//上拉
    private String upset= "1";//下拉
    int tj=3;
    String val;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dzcpkhxxdjl_list);
        initView();
	    init();
		
	}
	
	private void initView() {
		txt_header_title.setText(R.string.param196);
		 mProgressDialog = new ProgressDialog(this);
			
	        mListView = listView.getRefreshableView();
	        mListView.setDivider(new ColorDrawable(R.color.line_color));  
	        mListView.setDividerHeight(1);
	        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
							DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
					
					refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					if(refreshView.isHeaderShown()){
						int i=Integer.parseInt(upset);
						String time;
						val = edit_query.getText().toString();
						i++;
						 TAppYh user = BankApplication.mInstance.getCurrentUser();
					        String zjh=user.getSfz();
						 int listDataSize=listData.size();
						 if(listDataSize>0){
						 time = listData.get(0).getDate();
						}else{
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						 time = sdf.format(new Date());
						 
						}
						 upset =String.valueOf(i);
						 JSONObject content  =new JSONObject();
                         try {
                         	content.put("upset", upset);
                         	content.put("time", time);
                         	content.put("zjh", zjh);
                         	content.put("val", val);
                 		} catch (JSONException e) {
                 			// TODO Auto-generated catch block
                 			e.printStackTrace();
                 		}
                         mDzCpKhXxEtcPresenter.getDzcpEtcYcjUpListData(content.toString());
						Toast.makeText(getApplicationContext(), "下拉刷新",Toast.LENGTH_SHORT).show();
						
                      }else {
                    	  int i=Integer.parseInt(offset);
                    	  i = ++i;
                    	  TAppYh user = BankApplication.mInstance.getCurrentUser();
					        String zjh=user.getSfz();
                    	  int listDataSize=listData.size();
                    	  String time =listData.get(listDataSize-1).getDate();
                    	  offset = String.valueOf(i);
                    	  JSONObject content  =new JSONObject();
                          try {
                          	content.put("offset", offset);
                          	content.put("time", time);
                          	content.put("zjh", zjh);
                  		} catch (JSONException e) {
                  			// TODO Auto-generated catch block
                  			e.printStackTrace();
                  		}
                    	  mDzCpKhXxEtcPresenter.getDzcpEtcYcjListData(content.toString());
  						Toast.makeText(getApplicationContext(), "上拉刷新",Toast.LENGTH_SHORT).show();

							                    //上拉加载更多 业务代码
							                    //上拉加载更多 业务代码
							                }
					
				}
			});

	        listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
				@Override
				public void onLastItemVisible() {
					
				}
			});
	        
	        listData = new ArrayList<DzCpItem>();
	        
	        
	        mAdapter = new DzCpKhListViewAdapter(this, listData);

	        listView.setAdapter(mAdapter);
	        
	        listView.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
				   DzCpItem item=listData.get(position-1);
				   String appuuid=	item.getKey().replace(" ", "");
				   String zt=item.getZt();
				   if(zt.toString().trim().equals("ETC")){
					   Intent intent=new Intent();
					   intent.setClass(DzCpKhXxPosListActivity.this, DzCpKhXxEtcWcjXxActivity.class);
					   intent.putExtra("appuuid", appuuid);
					   intent.putExtra("zt", zt);
					   intent.putExtra("scbs", "1");
					   intent.putExtra("sczt","已成交");
					   startActivity(intent);
					   }
				   else{
					   Intent intent=new Intent();
					   intent.setClass(DzCpKhXxPosListActivity.this, DzCpKhXxYcJPosActivity.class);
					   intent.putExtra("appuuid", appuuid);
					   intent.putExtra("zt", zt);
					   intent.putExtra("scbs", "1");
					   startActivity(intent);
				   }
				}});
	        
	        listView.setMode(Mode.BOTH);
	        
	        registerForContextMenu(mListView);
	}
	private void init() {
		listData.clear();
		mDzCpKhXxEtcPresenter =new DzCpKhXxEtcPresenter(this);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String time = formatter.format(new  Date());
        TAppYh user = BankApplication.mInstance.getCurrentUser();
        String zjh=user.getSfz();
        JSONObject content  =new JSONObject();
        try {
        	content.put("offset", offset);
        	content.put("time", time);
        	content.put("zjh", zjh);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mDzCpKhXxEtcPresenter.getDzcpEtcYcjListData(content.toString());
		
		
	}
	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.hide();
	}

	@Override
	public void updateView(int type, Object Obj) {
		// TODO Auto-generated method stub
		if (type == ServerUtil.server_save){
			showMessage("保存成功");
		} else if (type == ServerUtil.server_delete){
			showMessage("删除成功");
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void updateList(List<DzCpkhXxDjEtc> mList) {
		// TODO Auto-generated method stub
	/*	dzcpkhxxetcList = mList;
		for (DzCpkhXxDjEtc mdzcpkhxxlList : mList){
			DzCpItem mImageItem = new DzCpItem();
	        mImageItem.setKey(mdzcpkhxxlList.getAppUuid());
	        mImageItem.setValue(mdzcpkhxxlList.getKhMc());
	        mImageItem.setSfz(mdzcpkhxxlList.getKhZjh());
	        mImageItem.setType(0);
	        int xgzt=mdzcpkhxxlList.getXgzt();
	        if(xgzt==0){
	        	 mImageItem.setZt("未上传");
	        }
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	        String dateString = formatter.format(mdzcpkhxxlList.getSqSj());
	        mImageItem.setDate(dateString);
	        listData.add(mImageItem);
		}
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		showMessage("刷新成功");*/
		}

	@Override
	public void updateListUp(List<DzCpkhXxDjEtc> mList) {
		// TODO Auto-generated method stub
		dzcpkhxxetcList = mList;
		for (DzCpkhXxDjEtc mdzcpkhxxlList : mList){
			DzCpItem mImageItem = new DzCpItem();
	        mImageItem.setKey(mdzcpkhxxlList.getAppUuid());
	        mImageItem.setValue(mdzcpkhxxlList.getKhMc());
	        mImageItem.setSfz(mdzcpkhxxlList.getKhZjh());
	        /*mImageItem.setType(0);*/
	        /*int sbzt=mdzcpkhxxlList.getSbZt();
	        if(sbzt==1){
	        	 mImageItem.setZt("已成交");
	        }*/
	       
	        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	        String dateString = formatter.format(mdzcpkhxxlList.getSqSj());
	        mImageItem.setDate(dateString);
	        String [] str = dateString.split(" "); 
	        mImageItem.setXsSj(str[0]);
	        mImageItem.setZt(mdzcpkhxxlList.getType());
	        mImageItem.setImg(mdzcpkhxxlList.getType());
	        listData.add(mImageItem);
		}
		 Collections.sort(listData, new Comparator<DzCpItem>() {
			   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			   private Date getDate(DzCpItem m) {
		           if (m == null || m.getDate() == null)
		               return null;
		           try {
		               return sdf.parse(m.getDate());
		           } catch (ParseException e) {
		               return null;
		           }
		       }
					@Override
					public int compare(DzCpItem lhs, DzCpItem rhs) {
						// TODO Auto-generated method stub
						Date d1 = getDate(lhs);
		                Date d2 = getDate(rhs);
		                if (d1 == null && d2 == null)
		                    return 0;
		 
		                if (d1 == null)
		                    return -1;
		                if (d2 == null)
		                    return 1;
		                return d2.compareTo(d1);
					}
		        });
				
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		showMessage("刷新成功");
	}
	public void queryClick(View arg0){
		query();
	}
	
	private void query(){
		listData.clear();
		 val = edit_query.getText().toString();
		 TAppYh user = BankApplication.mInstance.getCurrentUser();
		  String zjh=user.getSfz();
	        JSONObject content  =new JSONObject();
	        try {
	        	content.put("val", val);
	        	content.put("zjh", zjh);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		mDzCpKhXxEtcPresenter.getBdYcjserach(content.toString());
		
	}

	@Override
	public void success() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateListBm(List<TXtBm> mList) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void scsuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void AlertDialog() {
		// TODO Auto-generated method stub
		
	}

}
